﻿/**


 *

 */



package net.comm.servlet;



import java.io.*;
import java.net.URLEncoder;
import java.sql.*;
import java.util.Calendar;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;

import javax.servlet.*;
import javax.servlet.http.*;

import org.apache.log4j.Logger;
import org.sakaiproject.db.impl.BasicSqlService;



import net.comm.common.*;

import net.comm.user.bean.BaseUsers;
import net.comm.user.db.DbUsersService;
import net.comm.user.db.UsersServiceSqlMysql;
import net.comm.user.service.impl.DetailsServiceImpl;
import net.comm.user.service.impl.UserSysinfoServiceImpl;
import net.comm.user.web.form.DetailsForm;
import net.comm.user.web.form.UserSysinfoForm;
import net.comm.util.DatetimeUtil;
import net.comm.util.DbcpPool;
import net.comm.util.Function;
import net.comm.util.StringUtil;



public class LoginVerify extends HttpServlet {

	
	static Logger logger = Logger.getLogger(LoginVerify.class.getName());
	
	private static final long serialVersionUID = -3074767038737131093L;

	private static LinkedHashMap<String, String> Errmap;
	//map最大尺寸
	private static int Mapsize = 100;
	//超时时间
	private static int LMIN = 30;
	//尝试次数
	private static int LCNT = 4;

    @Override
	public void init() throws ServletException {
		// TODO Auto-generated method stub
		
    	Errmap = new LinkedHashMap<String, String>();
	}	
	
	/**

	 * @see javax.servlet.http.HttpServlet#doPost(HttpServletRequest,

	 *      HttpServletResponse)

	 */

	public void doPost(HttpServletRequest request, HttpServletResponse response)

			throws ServletException, IOException {
		
		if("".equals(GlbFinal.FOLDER_INSTALL)) {
			GlbFinal.FOLDER_INSTALL = request.getContextPath();
		}

		try {

			request.setCharacterEncoding("UTF-8");

		} catch (Exception e) {

			e.printStackTrace();
		}

		PrintWriter out = response.getWriter();
		// 输出页面头部

		response.setContentType("text/html");

		String[] js1 = new String[1];

		js1[0] = "/js/common.js";
		
		out.println(Function.getHtmlHead("用户登录",	"/images/printimg.gif", js1).toString());

		/**
		 *这里只要赋值需要更新的值
		 */
//		String certno = StringUtil.getValue(request.getParameter("certno"));
//		String certCode = (String)request.getSession().getAttribute("certCode");
//		
//		if(!certno.equals(certCode))
//		{
//			doInfo( "验证码错误", out);
//
//			return;
//		}
		
		// 初始化相应变量
		String nick = StringUtil.getValue(request.getParameter("nick"));
		String email = StringUtil.getValue(request.getParameter("email"));
		String password = StringUtil.getValue(request.getParameter("password"));
		String nexturl = StringUtil.getValue(request.getParameter("nexturl"));
		
		String loginsts = StringUtil.getValue(request.getParameter("loginsts"));
		
		
		//判断errmap中是存在 ，不存在则增加，存在则判断是否超过最长登录时间，超过，则删除，不超过则返回提示				
		String value = "";
		String key = "";
		int cnt = 0;
		String[] valArr = null;
		long lmin =0;
		for (Iterator<String> i = Errmap.keySet().iterator(); i.hasNext();) { 
			key = i.next(); 
			if(key.equals(email)||key.equals(nick)){
				value = Errmap.get(key);
				break;
			}
		} 	
		if(!value.equals("")){
			
			valArr = value.split(",");
			
			cnt = Integer.valueOf(valArr[0]);
			lmin = DatetimeUtil.getQuotDHMS(DatetimeUtil.getDatetime(),valArr[1],Calendar.MINUTE);
			//超过30分钟时间  则删除修改登录记录
			if(lmin > LMIN){
				
				value = "0," +  DatetimeUtil.getDatetime();
				Errmap.put(key, value);
			}else if( cnt > LCNT){//没超过规定时间 但大于登录尝试次数 则提示错误 返回

				doInfo( "错误登录次数超过5次，请1小时后再次尝试！", out);
				return;
			}
		}
		
		Connection cn = null;
		try
		{
			cn = DbcpPool.getConnection();
			DbcpPool.beginTran(cn);

			UsersServiceSqlMysql servSql = new UsersServiceSqlMysql();
			BasicSqlService  bSqlServ = new BasicSqlService();
			
			String sql = "";
			//取得FORM中传入的查询参数
			Object[] fields2 = new Object[1];
			
			if(!email.equals("")){
				
				fields2[0] = email;
				sql = servSql.getByEmailSql();
				
			}else if(!nick.equals("")){
				
				fields2[0] = nick;
				sql = servSql.getByNickSql();

			}else{
				
				doInfo( "请输入用户名或Email！", out);
				DbcpPool.rollBackTran(cn);
				DbcpPool.closeTran(cn);
				DbcpPool.returnConnection(cn);
				return;
			}
						
			List list = bSqlServ.dbRead(cn, sql, fields2, new DbUsersService());
			if(list.size() == 0){
				DbcpPool.rollBackTran(cn);
				DbcpPool.closeTran(cn);
				DbcpPool.returnConnection(cn);
				doInfo( "会员不存在！", out);
				return;
			}
			BaseUsers base = (BaseUsers)list.get(0);

			if(base.getStatus().equals(GlbFinal.USERSTS_CHECKING)||base.getStatus().equals(GlbFinal.USERSTS_CANCEL)
					||base.getStatus().equals(GlbFinal.USERSTS_EMAIL)||!Decode.Decode(base.getPassword()).equals(password)
					){
				if(Errmap.size() > Mapsize){
					for (Iterator<String> i = Errmap.keySet().iterator(); i.hasNext();) { 
						key = i.next(); 
						Errmap.remove(key);
						break;
					}
				} 
				
				//判断errmap中是存在 ，不存在则增加，存在则判断是否超过尝试登录次数，超过则返回，不超过则增加errmap				
				if(!email.equals("")){
					
					key = email;
				}else if(!nick.equals("")){
					
					key = nick;
				}
				if(Errmap.get(key) != null){
					Errmap.remove(key);
				}

				value = String.valueOf(cnt+1) + "," +  DatetimeUtil.getDatetime();
				Errmap.put(key, value);
			}
			
			if(!Decode.Decode(base.getPassword()).equals(password)){
				
				DbcpPool.rollBackTran(cn);
				DbcpPool.closeTran(cn);
				DbcpPool.returnConnection(cn);
				doInfo( "密码不正确！", out);
				//return;
			}
			
			if(base.getStatus().equals(GlbFinal.USERSTS_EMAIL)){
				
				DbcpPool.rollBackTran(cn);
				DbcpPool.closeTran(cn);
				DbcpPool.returnConnection(cn);
				doInfo( "会员没有激活！", out);
				return;
			}
			/*if(base.getStatus().equals(GlbFinal.USERSTS_CHECKING)){
				
				DbcpPool.rollBackTran(cn);
				DbcpPool.closeTran(cn);
				DbcpPool.returnConnection(cn);
				doInfo( "会员资料审核中！", out);
				return;
			}*/
			if(base.getStatus().equals(GlbFinal.USERSTS_CANCEL)){
				
				DbcpPool.rollBackTran(cn);
				DbcpPool.closeTran(cn);
				DbcpPool.returnConnection(cn);
				doInfo( "会员资料已经注销！", out);
				return;
			}
			
			//判断errmap中是否存在，存在则删除
			if(!key.equals("")){
				Errmap.remove(key);			
			}
			if(nexturl.equals("")){
				if(GlbFinal.FOLDER_INSTALL.equals("")) {
					nexturl = request.getContextPath() + "/users.do?action=main";
				} else {
					nexturl = GlbFinal.FOLDER_INSTALL + "/users.do?action=main";
				}
			} else {
				if(!nexturl.startsWith(request.getContextPath())) {
					nexturl = request.getContextPath() + nexturl;
				}
			}
			
			request.getSession().setAttribute(GlbFinal.SESSION_USERID, base.getUserID());
			request.getSession().setAttribute(GlbFinal.SESSION_NAME, base.getNick());
			request.getSession().setAttribute(GlbFinal.SESSION_USERTYPE, base.getType());
			
			
			/*
			 * 是否被投诉
			 */
		if(base.getStatus().equals(GlbFinal.USERSTS_CHECKING)){		
			response.sendRedirect(request.getContextPath()+"/shequ/shensu.jsp");
			return;
			}
			/*
			 * 是否首席客服
			 */
		if(base.getType().equals(GlbFinal.USER_KEFU)){		
			response.sendRedirect(request.getContextPath()+"/shenqing_faq/1_1.html");
			return;
			}


			if(loginsts.equals("1")){
				
				String cookpath = "/";
				//保存用户ID
				String cookieName=GlbFinal.SESSION_USERID;
				Cookie cookie=new Cookie(cookieName, String.valueOf(base.getUserID()));
				cookie.setMaxAge(7*24*60*60);
				cookie.setPath(cookpath);
				response.addCookie(cookie);
				
				//保存用户名
				if(base.getNick() != null){
					cookieName=GlbFinal.SESSION_NAME;
					cookie=new Cookie(cookieName, URLEncoder.encode(base.getNick(),"UTF-8"));
					cookie.setMaxAge(7*24*60*60);
					cookie.setPath(cookpath);
					response.addCookie(cookie);					
				}
						
				//保存用户类型
				cookieName=GlbFinal.SESSION_USERTYPE;
				cookie=new Cookie(cookieName, base.getType());
				cookie.setMaxAge(7*24*60*60);
				cookie.setPath(cookpath);
				response.addCookie(cookie);
			}
			
			DbcpPool.commitTran(cn);			
			DbcpPool.closeTran(cn);
			DbcpPool.returnConnection(cn);
		} catch(Exception ex) 
		{
			System.out.println("error="+ ex.getMessage());
			doInfo( "登录失败！", out);
			return;
		} finally {
			DbcpPool.returnConnection(cn);
		}
		out.println("</body>");
		out.println("</html>");

		response.sendRedirect(nexturl);

	}


	private void doInfo( String msginfo, PrintWriter out) throws UnsupportedEncodingException{


		System.out.println(msginfo);

		out.println("<script>");

		out.print("alert('");

		out.print(StringUtil.cnCodeTrans(msginfo));

		out.println("');");

		out.println("history.back();");

		out.println("</script>");

		out.println("</body>");

		out.println("</html>");


	}
}

